const BASE_62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
import BigNumber from "bignumber.js";
import { Logger, Hash } from "@hw-agconnect/base-ohos";

const DIVISOR = 62;
const BIT_MAX = 61;

const TAG = "HashUtil";

export class HashUtil {
  static hash(teamId: string, productId: string): string {
    let formatStr: string = "agc:" + teamId + "@" + productId;
    let hexRes = HashUtil.hashMd5(formatStr);
    hexRes = '0x' + hexRes;

    let intVaule = new BigNumber(hexRes);
    let res = HashUtil.encode(intVaule);
    return res;
  }

  private static hashMd5(formatStr: string) {
    try {
        return Hash.md5(formatStr);
    } catch (e) {
      Logger.error(TAG, "CryptoJS md5 error" + e?.message);
    }
    return "";
  }

  private static encode(num: BigNumber): string {
    let res: string = '';
    while (num.isGreaterThan(BIT_MAX)) {
      let remainder = num.modulo(DIVISOR);
      res = BASE_62.charAt(remainder.toNumber()) + res;
      num = num.dividedToIntegerBy(DIVISOR);
    }
    res = BASE_62.charAt(num.toNumber()) + res;
    return res;
  }
}
